import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import '../app_data_manager.dart';
import '../models/ddl_item.dart';

class MonthCalendarPage extends StatefulWidget {
  const MonthCalendarPage({Key? key}) : super(key: key);

  @override
  State<MonthCalendarPage> createState() => _MonthCalendarPageState();
}

class _MonthCalendarPageState extends State<MonthCalendarPage> {
  late Map<DateTime, List<DDLItem>> _events;
  DateTime _focusedDay = DateTime.now();
  DateTime? _selectedDay;
  late List<DDLItem> _allDDLs;
  
  // 预定义的颜色列表
  final List<Color> _urgentColors = [
    Colors.red,
    Colors.orange,
    Colors.deepOrange,
    Colors.redAccent,
    Colors.orangeAccent,
  ];

  final List<Color> _normalColors = [
    Colors.blue,
    Colors.teal,
    Colors.cyan,
    Colors.indigo,
    Colors.lightBlue,
  ];

  @override
  void initState() {
    super.initState();
    _allDDLs = AppDataManager().getDDLList();
    _events = _getEventsFromDDL();
  }

  Map<DateTime, List<DDLItem>> _getEventsFromDDL() {
    Map<DateTime, List<DDLItem>> events = {};
    for (var ddl in _allDDLs) {
      if (ddl.deadline != null) {
        final startDate = ddl.startDate ?? ddl.deadline!;
        final endDate = ddl.deadline!;
        
        // 添加开始日期到结束日期之间的所有日期
        var currentDate = startDate;
        while (!currentDate.isAfter(endDate)) {
          final date = DateTime(currentDate.year, currentDate.month, currentDate.day);
          events.putIfAbsent(date, () => []).add(ddl);
          currentDate = currentDate.add(const Duration(days: 1));
        }
      }
    }
    return events;
  }

  List<DDLItem> _getEventsForDay(DateTime day) {
    return _events[DateTime(day.year, day.month, day.day)] ?? [];
  }

  Color _getDDLColor(DDLItem ddl, List<DDLItem> dayEvents, int index) {
    if (ddl.isCompleted) return Colors.green;
    if (ddl.isAbandoned) return Colors.grey;
    
    // 获取当天所有DDL的索引
    final dayIndex = dayEvents.indexOf(ddl);
    
    // 根据是否紧急选择不同的颜色列表
    final colorList = ddl.isUrgent ? _urgentColors : _normalColors;
    return colorList[dayIndex % colorList.length];
  }

  Widget _buildDDLBar(DDLItem ddl, DateTime currentDay) {
    final startDate = ddl.startDate ?? ddl.deadline!;
    final endDate = ddl.deadline!;
    final currentDate = DateTime(currentDay.year, currentDay.month, currentDay.day);
    
    // 计算这个DDL在当前日期格子中的位置
    bool isStart = currentDate.isAtSameMomentAs(DateTime(startDate.year, startDate.month, startDate.day));
    bool isEnd = currentDate.isAtSameMomentAs(DateTime(endDate.year, endDate.month, endDate.day));
    
    // 获取当天的所有DDL
    final dayEvents = _getEventsForDay(currentDay);
    final dayIndex = dayEvents.indexOf(ddl);
    
    return Container(
      height: 16,
      margin: const EdgeInsets.symmetric(vertical: 1),
      decoration: BoxDecoration(
        color: _getDDLColor(ddl, dayEvents, dayIndex).withOpacity(0.8),
        borderRadius: BorderRadius.horizontal(
          left: Radius.circular(isStart ? 4 : 0),
          right: Radius.circular(isEnd ? 4 : 0),
        ),
      ),
      child: Center(
        child: Text(
          ddl.title,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 9,
            fontWeight: FontWeight.bold,
          ),
          overflow: TextOverflow.ellipsis,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 在每次构建时重新加载数据
    _allDDLs = AppDataManager().getDDLList();
    _events = _getEventsFromDDL();

    return Scaffold(
      appBar: AppBar(title: const Text('月视图日历')),
      body: Column(
        children: [
          TableCalendar<DDLItem>(
            firstDay: DateTime.utc(2000, 1, 1),
            lastDay: DateTime.utc(2100, 12, 31),
            focusedDay: _focusedDay,
            selectedDayPredicate: (day) => isSameDay(_selectedDay, day),
            eventLoader: _getEventsForDay,
            calendarFormat: CalendarFormat.month,
            onDaySelected: (selectedDay, focusedDay) {
              setState(() {
                _selectedDay = selectedDay;
                _focusedDay = focusedDay;
              });
              final events = _getEventsForDay(selectedDay);
              if (events.isNotEmpty) {
                showDialog(
                  context: context,
                  builder: (context) => AlertDialog(
                    title: Text('${selectedDay.year}-${selectedDay.month}-${selectedDay.day} 的DDL'),
                    content: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: events.map((e) => ListTile(
                        title: Text(e.title),
                        subtitle: Text('开始: ${e.startDate?.toString() ?? "未设置"}\n截止: ${e.deadline?.toString() ?? "未设置"}'),
                        trailing: e.isUrgent ? const Icon(Icons.warning, color: Colors.red) : null,
                      )).toList(),
                    ),
                    actions: [
                      TextButton(
                        onPressed: () => Navigator.of(context).pop(),
                        child: const Text('关闭'),
                      ),
                    ],
                  ),
                );
              }
            },
            calendarStyle: CalendarStyle(
              markersMaxCount: 3,
              markerDecoration: const BoxDecoration(
                color: Colors.transparent,
                shape: BoxShape.circle,
              ),
              cellMargin: EdgeInsets.zero,
              cellPadding: EdgeInsets.zero,
              outsideDaysVisible: false,
              weekendTextStyle: const TextStyle(color: Colors.red),
              holidayTextStyle: const TextStyle(color: Colors.red),
              defaultTextStyle: const TextStyle(color: Colors.black),
              selectedDecoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.2),
                shape: BoxShape.rectangle,
              ),
              todayDecoration: BoxDecoration(
                color: Colors.blue.withOpacity(0.1),
                shape: BoxShape.rectangle,
              ),
            ),
            headerStyle: const HeaderStyle(
              formatButtonVisible: false,
              titleCentered: true,
            ),
            calendarBuilders: CalendarBuilders(
              defaultBuilder: (context, date, _) {
                final events = _getEventsForDay(date);
                final displayEvents = events.length > 3 ? events.sublist(0, 3) : events;
                
                return Container(
                  margin: const EdgeInsets.all(1),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey.shade300),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Column(
                    children: [
                      // 日期数字部分
                      Container(
                        height: 24,
                        alignment: Alignment.center,
                        child: Text(
                          date.day.toString(),
                          style: TextStyle(
                            color: date.weekday == 6 || date.weekday == 7 ? Colors.red : Colors.black,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      // DDL卡片部分
                      if (displayEvents.isNotEmpty)
                        Expanded(
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              ...displayEvents.map((e) => _buildDDLBar(e, date)),
                              if (events.length > 3)
                                Container(
                                  height: 16,
                                  margin: const EdgeInsets.symmetric(vertical: 1),
                                  child: const Center(
                                    child: Text(
                                      '...',
                                      style: TextStyle(
                                        color: Colors.grey,
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                            ],
                          ),
                        ),
                    ],
                  ),
                );
              },
              dowBuilder: (context, day) {
                final weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                return Center(
                  child: Text(
                    weekdays[day.weekday - 1],
                    style: TextStyle(
                      color: day.weekday == 6 || day.weekday == 7 ? Colors.red : Colors.black,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                );
              },
            ),
            daysOfWeekHeight: 30,
            rowHeight: 80,
          ),
          if (_selectedDay != null)
            Expanded(
              child: ListView(
                children: _getEventsForDay(_selectedDay!).map((e) => ListTile(
                  title: Text(e.title),
                  subtitle: Text('开始: ${e.startDate?.toString() ?? "未设置"}\n截止: ${e.deadline?.toString() ?? "未设置"}'),
                  trailing: e.isUrgent ? const Icon(Icons.warning, color: Colors.red) : null,
                )).toList(),
              ),
            ),
        ],
      ),
    );
  }
}
